package com.chuangan.releasetask.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chuangan.releasetask.Utils.JwtUtil;
import com.chuangan.releasetask.Utils.ResultVOUtil;
import com.chuangan.releasetask.VO.ResultVO;
import com.chuangan.releasetask.pojo.User;
import com.chuangan.releasetask.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;


/**
 * @Author: jinLong
 * @Date: 2020/8/19 17:34
 * @Version 1.0
 */
@Component
public class JwtFilter extends HandlerInterceptorAdapter  {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        String msg = "系统异常";
        // 成功标识
        boolean flag = true;
        //失败标识
        boolean fail = false;
        // 错误码
        int RtnValue = 9099;
        //返回对象
        ResultVO resultVO = null;
        //请求头中获取token
        String token = request.getHeader("token");
        PrintWriter out = response.getWriter();
        //1.如果token为空，返回token为空
        if (token==null) {
            out.print(JSON.toJSONString(ResultVOUtil.error(1006, "令牌为空，请登录!")));
            return fail;
        }
        //解析Token，如果通过，证明没有过期
        JSONObject pojo = jwtUtil.validateJWT(token);
        if (pojo.getBooleanValue("Success")) {
            // 解析成功
            Claims claims = (Claims) pojo.get("Claims");
            String userAccount = claims.getId();
            User loginUser = userService.findOneUser(userAccount);
            String redisToken = redisTemplate.opsForValue().get(userAccount + "token");
            if (redisToken == null) {
                out.print(JSON.toJSONString(ResultVOUtil.error(1005, "令牌过期")));
                return fail;
            }
            // 与数据库里的比较
            if (token.equals(redisToken) || redisToken != null) {
                request.getSession().setAttribute("loginUser", loginUser);
                out.print(JSON.toJSONString(ResultVOUtil.success()));
                out.flush();
                out.close();
                return flag;
            } else {
                out.print(JSON.toJSONString(ResultVOUtil.error(1007, "令牌不匹配，请重新登录!")));
                out.flush();
                out.close();
                return fail;
            }
        } else {
            // 解析失败
            RtnValue = (int) pojo.get("ErrCode");
            switch (RtnValue) {
                case 1005:
                    msg = "令牌过期";
                    break;
                case 1004:
                    msg = "未登录";
                    break;
                default:
                    break;
            }
            resultVO = ResultVOUtil.error(RtnValue, msg);
            out.print(JSON.toJSONString(resultVO));
            out.flush();
            out.close();
        }
        return fail;
    }


}
